'''

Case Type： 数据库系统
Case Name： 持续操作表，手工删除表文件读写权限，令数据库用户无法访问
Create At:  2020/06/28
@zou_jialiang0505328126
Descption:  1.	创建表，并写入数据2.删除对应表文件读写权限,重新登陆数据库(清除缓存)3.写入数据

history：
created： 2020/06/28  created by @wan005
'''
import unittest
import sys
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common


class Modifytablefilepermission(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case060.py start------------')
        self.DN1_PATH = macro.DB_INSTANCE_PATH
        self.rootNode = Node()
        self.dbUserNode = Node(node='dbuser')
        self.com = Common()

    def test_Modify_Table_File_Permission(self):
        self.log.info('----------------------------创建表，并写入数据-----------------------------')
        self.t_name = 'test_table'
        msg = self.com.createLargeNumTable(self.dbUserNode, self.t_name, 1, 10)
        self.log.info(msg)

        self.log.info("querry table position")
        querry_tbl_sql = f'''select oid,relname from pg_class where relname = {self.t_name};'''
        result = self.sh.executDbSql(querry_tbl_sql)
        self.log.info(result[0][0])

        querry_tbl_sql = 'select pg_relation_filepath(' + result[0][0] + '::regclass);'
        tbl_position = self.sh.executDbSql(querry_tbl_sql)
        self.tbl_position = tbl_position[0][0]
        self.log.info(self.tbl_position)

        self.log.info('----------------------------修改权限-----------------------------')
        chmodfile_cmd = 'chmod 000 ' + self.DN1_PATH + '/' + self.tbl_position
        self.log.info(chmodfile_cmd)
        msg = self.rootNode.sh(chmodfile_cmd)
        self.log.info(msg)

        self.log.info('----------------------------重启以清缓存-----------------------------')
        is_stoped = self.sh.stopDbCluster()
        self.assertTrue(is_stoped)
        is_started = self.sh.startDbCluster()
        self.assertTrue(is_started)

        self.log.info('----------------------------插入数据-----------------------------')
        self.log.info("insert data")
        msg = self.com.createLargeNumTable(self.dbUserNode, self.t_name, 1, insert_sign=True)
        self.log.info(msg)

    def tearDown(self):
        chmodfile_cmd = 'chmod 600 ' + self.DN1_PATH + '/' + self.tbl_position
        self.log.info(chmodfile_cmd)
        self.rootNode.sh(chmodfile_cmd)

        # 清理环境，删除表
        msg = self.com.createLargeNumTable(self.dbUserNode, self.t_name, del_sign=True)
        self.log.info(msg)
        self.log.info('this is tearDown')
